package com.mac.intellect_flow.admin.controller.system;

import com.mac.intellect_flow.constant.CommonConstant;
import com.mac.intellect_flow.reply.PageParam;
import com.mac.intellect_flow.reply.PageResult;
import com.mac.intellect_flow.reply.R;
import com.mac.intellect_flow.sys.entity.SysDept;
import com.mac.intellect_flow.sys.service.SysDeptService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 部门信息
 * 
 * @author mac
 */
@Tag(name = "部门管理")
@RestController
@RequestMapping("/system/dept")
public class SysDeptController{
    @Autowired
    private SysDeptService deptService;

    /**
     * 获取部门列表
     */
    @Operation(summary = "部门列表")
    @PreAuthorize("@ps.hasPermi('system:dept:list')")
    @GetMapping("/list")
    public R<PageResult<SysDept>> list(SysDept dept, PageParam pageParam) {
        return R.success(deptService.queryPage(dept, pageParam));
    }

    /**
     * 查询部门列表（排除节点）
     */
    @Operation(summary = "查询部门列表（排除节点）")
    @PreAuthorize("@ps.hasPermi('system:dept:list')")
    @GetMapping("/list/exclude/{deptId}")
    public R excludeChild(@PathVariable(value = "deptId", required = false) Long deptId) {
        List<SysDept> depts = deptService.selectDeptList(new SysDept());
        depts.removeIf(d -> d.getDeptId().intValue() == deptId || ArrayUtils.contains(StringUtils.split(d.getAncestors(), ","), deptId + ""));
        return R.success(depts);
    }

    /**
     * 获取部门下拉树列表
     */
    @Operation(summary = "获取部门下拉树列表")
    @GetMapping("/treeselect")
    public R treeselect(SysDept dept) {
        List<SysDept> depts = deptService.selectDeptList(dept);
        return R.success(deptService.buildDeptTreeSelect(depts));
    }

    /**
     * 根据部门编号获取详细信息
     */
    @Operation(summary = "根据部门编号获取详细信息")
    @PreAuthorize("@ps.hasPermi('system:dept:query')")
    @GetMapping(value = "/{deptId}")
    public R getInfo(@PathVariable Long deptId) {
        deptService.checkDeptDataScope(deptId);
        return R.success(deptService.selectDeptById(deptId));
    }

    /**
     * 新增部门
     */
    @Operation(summary = "新增部门")
    @PreAuthorize("@ps.hasPermi('system:dept:add')")
    @PostMapping
    public R add(@Validated @RequestBody SysDept dept) {
        if (!deptService.checkDeptNameUnique(dept)) {
            return R.error("新增部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        }
        return R.success(deptService.insertDept(dept));
    }

    /**
     * 修改部门
     */
    @Operation(summary = "修改部门")
    @PreAuthorize("@ps.hasPermi('system:dept:edit')")
    @PutMapping
    public R edit(@Validated @RequestBody SysDept dept) {
        Long deptId = dept.getDeptId();
        deptService.checkDeptDataScope(deptId);
        if (!deptService.checkDeptNameUnique(dept)) {
            return R.error("修改部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        } else if (dept.getParentId().equals(deptId)) {
            return R.error("修改部门'" + dept.getDeptName() + "'失败，上级部门不能是自己");
        } else if (StringUtils.equals(CommonConstant.EXCEPTION, dept.getStatus()) && deptService.selectNormalChildrenDeptById(deptId) > 0) {
            return R.error("该部门包含未停用的子部门！");
        }
        return R.success(deptService.updateDept(dept));
    }

    /**
     * 删除部门
     */
    @Operation(summary = "删除部门")
    @PreAuthorize("@ps.hasPermi('system:dept:remove')")
    @DeleteMapping("/{deptId}")
    public R remove(@PathVariable Long deptId) {
        if (deptService.hasChildByDeptId(deptId)) {
            return R.error("存在下级部门,不允许删除");
        }
        if (deptService.checkDeptExistUser(deptId)) {
            return R.error("部门存在用户,不允许删除");
        }
        deptService.checkDeptDataScope(deptId);
        return R.success(deptService.deleteDeptById(deptId));
    }

    /**
     * 获取部门树列表
     */
    @Operation(summary = "获取部门树列表")
    //@PreAuthorize("@ps.hasPermi('system:dept:list')")
    @GetMapping("/dept/tree")
    public R deptTree(SysDept dept) {
        return R.success(deptService.selectDeptTreeList(dept));
    }
}
